package com.bustle.ejb.service;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;

import com.bustle.ejb.entity.Authentication;
import com.bustle.ejb.entity.User;
import com.bustle.ejb.service.dao.AuthenticationDao;
import com.bustle.ejb.service.dao.UserDao;

@Local
public interface AuthenticationManager
{
  public User authenticate(String aLogin, String aPassword) throws AuthenticationException;
  public User createUser(String aLogin, String aPassword) throws AuthenticationException;

  public User getUser(int anId);
  public void updateUser(User aUser);

  @Stateless
  public class DefaultAuthenticationManager implements AuthenticationManager
  {
    @Override
    public User authenticate(String aLogin, String aPassword) throws AuthenticationException
    {
      Authentication authentication = authenticationDao.retrieve(aLogin);
      if (authentication == null)
      {
        throw new AuthenticationException("Unable to authenticate unknown " + aLogin);
      }
      if (!authentication.getPassword().equals(aPassword))
      {
        throw new AuthenticationException("Unable to authenticate " + aLogin);
      }
      return authentication.getUser();
    }

    @Override
    public User createUser(String aLogin, String aPassword) throws AuthenticationException
    {
      if (authenticationDao.retrieve(aLogin) == null)
      {
        User user = new User();
        Authentication authentication = new Authentication();
        authentication.setLogin(aLogin);
        authentication.setPassword(aPassword);
        authentication.setUser(user);
        userDao.create(user);
        authenticationDao.create(authentication);
        return user;
      }
      throw new AuthenticationException("Unable to create a User with existing login " + aLogin);
    }

    @Override
    public User getUser(int anId)
    {
      return userDao.retrieve(anId);
    }

    @Override
    public void updateUser(User aUser)
    {
      userDao.update(aUser);
    }

    @EJB
    protected AuthenticationDao authenticationDao;
    @EJB
    protected UserDao userDao;
  }
}
